﻿using L6_RegionNavigation.NavigateJournal.Models;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Navigation.Regions;
using System.Collections.ObjectModel;

namespace L6_RegionNavigation.NavigateJournal.ViewModels;

public class MainWindowViewModel : BindableBase
{
    private readonly IRegionManager regionManager;

    private IRegionNavigationJournal _journal;
    public IRegionNavigationJournal Journal
    {
        get => _journal;
        set => SetProperty(ref _journal, value);
    }

    public ObservableCollection<Person> People { get; set; }

    public DelegateCommand<Person> ShowPerson { get; set; }

    public DelegateCommand GoBack { get; set; }

    public DelegateCommand GoForward { get; set; }

    public DelegateCommand LoadedCommand { get; set; }

    public MainWindowViewModel(IRegionManager regionManager)
    {
        this.regionManager = regionManager;

        People = new ObservableCollection<Person>();
        for (int i = 0; i < 5; i++)
        {
            Person person = new Person();
            person.Id = i;
            person.Name = "姓名" + i.ToString();
            person.Age = 20 + i;

            People.Add(person);
        }

        ShowPerson = new DelegateCommand<Person>(ExcuteShowPerson);
        GoBack = new DelegateCommand(ExcuteGoBack, CanExcuteGoBack).ObservesProperty(() => Journal);
        GoForward = new DelegateCommand(ExcuteGoForward, CanExcuteGoForward).ObservesProperty(() => Journal);
        LoadedCommand = new DelegateCommand(ExcuteLoadedCommand);
    }

    private void ExcuteShowPerson(Person p)
    {
        NavigationParameters parameters = new NavigationParameters();
        parameters.Add("model", p);

        this.regionManager.RequestNavigate("ContentRegion", "PersonAttributeView", parameters);
    }

    private void ExcuteGoBack()
    {
        Journal?.GoBack();
    }

    private bool CanExcuteGoBack()
    {
        return Journal != null && Journal.CanGoBack;
    }

    private void ExcuteGoForward()
    {
        Journal?.GoForward();
    }

    private bool CanExcuteGoForward()
    {
        return Journal != null && Journal.CanGoForward;
    }

    private void ExcuteLoadedCommand()
    {
        IRegionNavigationService service = regionManager.Regions["ContentRegion"].NavigationService;
        service.Navigated -= RaiseJournalChanged;
        service.Navigated += RaiseJournalChanged;

        Journal = service.Journal;
    }

    private void RaiseJournalChanged(object sender, RegionNavigationEventArgs e)
    {
        RaisePropertyChanged(nameof(Journal));
    }
}